package com.shwread.android.qysw.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.ciko.code.base.BaseActicity;
import com.ciko.code.bean.LeaderList;
import com.ciko.code.bean.MyBusinessTripBean;
import com.ciko.code.http.BaseResponse;
import com.ciko.code.http.Req.ConsentOutsideApply;
import com.ciko.code.http.Req.QryWorkOutsideInfos;
import com.ciko.code.http.Req.RefuseOutsideApply;
import com.ciko.code.http.Req.SignWorkOutsideInfos;
import com.ciko.code.utils.DateUtil;
import com.ciko.code.views.PullListView;
import com.mywork.WorkUIKit;
import com.shwread.android.qysw.adapter.ApprovalProcessAdapter;
import com.shwread.android.qysw.bean.BusinessEvent;
import com.shwread.android.qysw10000243.R;
import com.shwread.android.ui.dialog.ApprovalDommentsDialog;
import com.shwread.android.ui.dialog.ApprovalListener;
import com.shwread.android.ui.dialog.CommonDialog;
import com.shwread.httpsdk.util.NetUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * 因公外出信息详情页面
 */

public class MyBusinessTripDetailActivity extends BaseActicity {
    private TextView state_approver, tvMyFieldWorkDetaCusName, tvMyFieldWorkDetaTime, tvMyFieldWorkDetaAddress,
            tvMyFieldWorkDetaReason, real_time, real_address;
    private PullListView lv_workFlow;
    private Button btnReject, btnAccept, real_sign_in, visit_feedback_button;
    private TextView content_feedback;

    private LinearLayout ll_acceptOrreject, businessTrip_sign_in,real_map_adress,Visit_feedback;

    private int type = -1;//根据传递的type值，判断是我发送的外出，还是我收到的外出

    private String ApprovalStatus;//审批状态
    private final int SEND = 1;//发出的因公外出
    private final int RECEIVE = 2;//收到的因公外出

    private MyBusinessTripBean fb;
    private MyBusinessTripBean mb;
    private int  nextUserId;
    private String nextUserName;

    private ApprovalDommentsDialog approvalDommentsDialog;

    private static AMapLocationClient mLocationClient   = null;
    private AMapLocationListener mLocationListener = null;
    private AMapLocationClientOption mLocationOption   = null;

    private static String             actualAddr;
    private static Double             actualLon;
    private static Double             actualLat;
    private String feedback;
    private ApprovalProcessAdapter approvalProcessAdapter;

    private List<LeaderList> recodeListEntityList = new ArrayList<LeaderList>();
    private ProgressDialog progressDialog1;

    private static double EARTH_RADIUS = 6378.137;

    private long nowTimestamp=0;
    private String beginTime;
    private long beginTimestamp=0;

    private CommonDialog dialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //注册EventBus
        EventBus.getDefault().register(this);
    }
    @Override
    protected void initTopBar() {
        setTitle("因公外出详情");
        enableNavLeftImg();
    }
    //接收用EventBus传递的数据
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(BusinessEvent message){
        nextUserId=message.getNextUserId();
        Log.e("nextUserId",String.valueOf(nextUserId));
        nextUserName=message.getNextUserName();
        Log.e("mb",mb.toString());

        List<String> id=new ArrayList<String>();
        for(int i=0;i<mb.getLeaderList().size();i++){
            LeaderList le=mb.getLeaderList().get(i);
            id.add(String.valueOf(le.getPreUserId()));
        }
        if (id.contains(String.valueOf(nextUserId))||Integer.parseInt(WorkUIKit.getUserId())==nextUserId){
            Toast.makeText(MyBusinessTripDetailActivity.this,"下一个审批人与之前审批人相同",Toast.LENGTH_SHORT).show();
        }else {
            doRequestHttp(new ConsentOutsideApply(fb.getId(), approvalDommentsDialog.getEidtText(), 1, nextUserId,nextUserName));
            progressDialog.show();
        }

    }
    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_my_business_trip);
        fb = (MyBusinessTripBean) getIntent().getSerializableExtra("bean");
        type = this.getIntent().getIntExtra("type", -1);
        Log.e("recodeListEntityList",recodeListEntityList.toString());

    }

    @Override
    protected void initView() {
        progressDialog1 = new ProgressDialog(this);
        state_approver = (TextView) findViewById(R.id.state_approver);
        tvMyFieldWorkDetaCusName = (TextView) findViewById(R.id.tvMyFieldWorkDetaCusName);
        tvMyFieldWorkDetaTime = (TextView) findViewById(R.id.tvMyFieldWorkDetaTime);
        tvMyFieldWorkDetaAddress = (TextView) findViewById(R.id.tvMyFieldWorkDetaAddress);
        tvMyFieldWorkDetaReason = (TextView) findViewById(R.id.tvMyFieldWorkDetaReason);
        real_time = (TextView) findViewById(R.id.real_time);
        real_address = (TextView) findViewById(R.id.real_address);

        lv_workFlow = (PullListView) findViewById(R.id.lv_workFlow);

        btnReject = (Button) findViewById(R.id.btnReject);
        btnAccept = (Button) findViewById(R.id.btnAccept);
        real_sign_in = (Button) findViewById(R.id.real_sign_in);
        visit_feedback_button = (Button) findViewById(R.id.visit_feedback_button);

        content_feedback = (TextView) findViewById(R.id.content_feedback);

        ll_acceptOrreject = (LinearLayout) findViewById(R.id.ll_acceptOrreject);
        businessTrip_sign_in = (LinearLayout) findViewById(R.id.businessTrip_sign_in);
        real_map_adress= (LinearLayout) findViewById(R.id.real_map_adress);
        Visit_feedback= (LinearLayout) findViewById(R.id.Visit_feedback);

    }

    private void setVisitAdress() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        real_time.setText(str);
        mLocationClient = new AMapLocationClient(getApplicationContext());

        mLocationOption = new AMapLocationClientOption();
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位

        mLocationListener = new AMapLocationListener()
        {
            @Override
            public void onLocationChanged(final AMapLocation aMapLocation) {
                if (aMapLocation != null && aMapLocation.getErrorCode() == 0)
                {
                    real_address.post(new Runnable()
                    {
                        @Override
                        public void run() {
                            actualAddr = aMapLocation.getAddress();
                            real_address.setText(actualAddr);
                            actualLon = aMapLocation.getLongitude();
                            Log.e("actualLon+1",actualLon+"");
                            Log.e("actualLat+1",actualLat+"");
                            actualLat = aMapLocation.getLatitude();

                        }
                    });

                    mLocationClient.stopLocation();
                }
            }
        };
        mLocationClient.setLocationListener(mLocationListener);
        mLocationClient.startLocation();
    }

    @Override
    protected void initAdapter() {

    }



    @Override
    protected void initDates() {
        tvMyFieldWorkDetaCusName.setText(Html.fromHtml(
                "<font color='#2b2b2b'>" + fb.getCustName() + "</font>"));
        Log.e("getBeginVisitTime",fb.getBeginVisitTime());
        Log.e("getEndVisitTime",fb.getEndVisitTime());
        tvMyFieldWorkDetaTime.setText(Html.fromHtml("<font color='#8c8c8c'></font>" +
                "<font color='#2b2b2b'>" +translateTime(Long.parseLong(fb.getBeginVisitTime())) + "    至    " + "<font color='#2b2b2b'>" +translateTime(Long.parseLong(fb.getEndVisitTime())) + "</font>"));
        tvMyFieldWorkDetaAddress.setText(Html.fromHtml("<font color='#2b2b2b'>" + fb.getCustAddr() + "</font>"));
        tvMyFieldWorkDetaReason.setText(Html.fromHtml(
                "<font color='#2b2b2b'>" + fb.getVisitCause() + "</font>"));
        switch (fb.getStatus()){
            case 0:
                state_approver.setText("当前状态：待审批");
                break;
            case 1:
                state_approver.setText("当前状态：待签到");
                break;
            case 2:
                state_approver.setText("当前状态：待反馈");
                break;
            case 3:
                state_approver.setText("当前状态：已反馈");
                break;
            case 4:
                state_approver.setText("当前状态：审批不通过");
                break;
        }
        doRequestHttp(new QryWorkOutsideInfos(fb.getId()));

        //获取系统当前时间
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String noewTime=df.format(new Date());
        nowTimestamp=com.ciko.code.utils.Util.getStringtoDate(noewTime).getTime();
        Log.e("nowTimestamp",nowTimestamp+"");
        String time = DateUtil.longToDate(Long.parseLong(fb.getBeginVisitTime()), 4);
        String[] strings = time.split(" ");
        beginTime= strings[0];
        String beginDate;
        beginDate =beginTime + " " + "23:59:59";
        try {
            Date date = df.parse(beginDate);
            beginTimestamp=date.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Log.e("beginTimestamp",beginTimestamp+"");
        if (nowTimestamp>beginTimestamp){
            real_sign_in.setText("已过期");
            real_sign_in.setEnabled(false);
        }

    }

    @Override
    public void onRequestStart(String tag) {
        super.onRequestStart(tag);
    }

    @Override
    public void onResponseSuccess(BaseResponse<?> response, String tag) {
        switch (tag) {
            case "QryWorkOutsideInfos":
                mb= (MyBusinessTripBean) response.getReturnObject();
                recodeListEntityList=mb.getLeaderList();
                List<String> preId=new ArrayList<>();
                for (int i = 0; i < recodeListEntityList.size(); i++) {
                    LeaderList lee=recodeListEntityList.get(i);
                    preId.add(String.valueOf(lee.getPreUserId()));
                }
                if (SEND==type){
                    if (1 == fb.getStatus()) {
                        businessTrip_sign_in.setVisibility(View.VISIBLE);
                        setVisitAdress();

                    }else if(2==fb.getStatus()){
                        businessTrip_sign_in.setVisibility(View.VISIBLE);
                        real_sign_in.setVisibility(View.GONE);
                        setVisitAdress();
                        visit_feedback_button.setVisibility(View.VISIBLE);

                    }else if(3==fb.getStatus()){
                        businessTrip_sign_in.setVisibility(View.VISIBLE);
                        real_sign_in.setVisibility(View.GONE);
                        setVisitAdress();
                        Visit_feedback.setVisibility(View.VISIBLE);
                        content_feedback.setText("\u3000\u3000"+fb.getFeedback());
                    }
                }
                else if (type == RECEIVE) {
                    if (0 == fb.getStatus()) {
                        ll_acceptOrreject.setVisibility(View.VISIBLE);
                    }else if (1==fb.getStatus()&&!preId.contains(WorkUIKit.getUserId())){
                        ll_acceptOrreject.setVisibility(View.VISIBLE);
                    }
                    else if(2==fb.getStatus()){
                        businessTrip_sign_in.setVisibility(View.VISIBLE);
                        real_sign_in.setVisibility(View.GONE);
                        setVisitAdress();

                    }else if(3==fb.getStatus()){
                        businessTrip_sign_in.setVisibility(View.VISIBLE);
                        real_sign_in.setVisibility(View.GONE);
                        setVisitAdress();
                        Visit_feedback.setVisibility(View.VISIBLE);
                        content_feedback.setText("\u3000\u3000"+fb.getFeedback());
                    }
                }

                approvalProcessAdapter = new ApprovalProcessAdapter(this, recodeListEntityList, com.mywork.R.layout.item_list_receive_business, mb);
                lv_workFlow.setAdapter(approvalProcessAdapter);


                break;
            case "ConsentOutsideApply":
                if (progressDialog.isShowing()){
                    progressDialog.dismiss();
                }
                showToast("同意审批成功");
//                ll_acceptOrreject.setVisibility(View.GONE);
                finish();
                break;
            case "RefuseOutsideApply":
                if (progressDialog.isShowing()){
                    progressDialog.dismiss();
                }
                showToast("拒绝审批成功");

                finish();
                break;
            case "SignWorkOutsideInfos":
                if (progressDialog.isShowing()){
                    progressDialog.dismiss();
                }
                showToast("签到成功");
                state_approver.setText("当前状态：待反馈");
                real_sign_in.setVisibility(View.GONE);
                visit_feedback_button.setVisibility(View.VISIBLE);
//                finish();
                break;

        }


    }

    @Override
    public void onResponseFail(String tag, int resultCode) {
        switch (tag){
            case "ConsentOutsideApply":
                if (progressDialog.isShowing()){
                    progressDialog.dismiss();
                }
                showToast("同意审批失败");
                finish();
                break;
            case "RefuseOutsideApply":
                if (progressDialog.isShowing()){
                    progressDialog.dismiss();
                }
                showToast("拒绝审批失败");
                finish();
                break;
            case "SignWorkOutsideInfos":
                if (progressDialog.isShowing()){
                    progressDialog.dismiss();
                }
                showToast("签到失败");
//                finish();
                break;

        }

    }
    @Override
    protected void initListener() {
        btnAccept.setOnClickListener(this);
        btnReject.setOnClickListener(this);
        real_map_adress.setOnClickListener(this);
        real_sign_in.setOnClickListener(this);
        visit_feedback_button.setOnClickListener(this);

    }

    public boolean isEmpty(String str) {
        if (null == str || str.equals("null") || str.length() == 0) return true;
        else return false;
    }
    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == btnAccept) {
            approvalDommentsDialog = new ApprovalDommentsDialog(MyBusinessTripDetailActivity.this, new ApprovalListener() {
                @Override
                public void clickOk() {
                    progressDialog.show();
                    doRequestHttp(new ConsentOutsideApply(fb.getId(), approvalDommentsDialog.getEidtText(), 0, 0, " "));
                }

                @Override
                public void clickNext() {

                }
            });
            approvalDommentsDialog.show();
        } else if (v == btnReject) {
            approvalDommentsDialog = new ApprovalDommentsDialog(MyBusinessTripDetailActivity.this, new ApprovalListener() {
                @Override
                public void clickOk() {
                    progressDialog.show();
                    doRequestHttp(new RefuseOutsideApply(fb.getId(), approvalDommentsDialog.getEidtText()));

                }

                @Override
                public void clickNext() {

                }
            });
            approvalDommentsDialog.show();
        }else if (v==real_map_adress){
            //跳转到高德地图
            Intent intent = new Intent(MyBusinessTripDetailActivity.this, SignInActivity.class);
            startActivity(intent);
        }else if(v==real_sign_in){
            //判断网络情况
            if (!NetUtil.isNetworkConnected(MyBusinessTripDetailActivity.this))
            {
                dialog=new CommonDialog(MyBusinessTripDetailActivity.this) {
                    @Override
                    protected void clickOk(View v) {
                        super.clickOk(v);
                    }
                };
                dialog.setButtonText("确定");
                dialog.setBtnCancelGone();
                dialog.setTvText("当前网络状况不佳，获取位置失败，请稍后重试");
                dialog.show();
                return;
            }else {
                clickQiandao();
            }
        }else if (v==visit_feedback_button){

            Intent intent = new Intent(MyBusinessTripDetailActivity.this,MyFeedBackActivity.class);
            intent.putExtra("outsideId",fb.getId());
            startActivityForResult(intent,100);
        }

    }
    //判断签到是否在拜访地址区域内
    private void clickQiandao() {
        String dis = getDistance(mb.getCustLon(), mb.getCustLat(), String.valueOf(actualLon),String.valueOf(actualLat) );
        Log.e("actualLat",String.valueOf(actualLat));
        Log.e("actualLon",String.valueOf(actualLon));
        Log.e("getCustLat",mb.getCustLat());
        Log.e("getCustLon",mb.getCustLon());


        Log.e("distanceStr",String.valueOf(Double.valueOf(dis) * 1000000));
        Log.e("mb.getDistance()",String.valueOf(mb.getDistance()));
        if (Double.valueOf(dis) * 1000>mb.getDistance()) {
            dialog=new CommonDialog(MyBusinessTripDetailActivity.this) {
                @Override
                protected void clickOk(View v) {
                    super.clickOk(v);
                }

                @Override
                protected void clickCancel(View v) {
                    dialog.dismiss();
                    Intent intent = new Intent(MyBusinessTripDetailActivity.this, ReLocationActivity.class);
                    MyBusinessTripDetailActivity.this.startActivity(intent);
                }
            };
            dialog.setButtonText("确定");//----ok
//            dialog.setCloseBtnVisiable();
            dialog.setButtonCancelText("重新定位");//--------cancel
            dialog.setTvText("当前位置不在拜访地址区域内");
            dialog.show();
            return;
        }else {
            progressDialog.show();
            //签到接口调用进行签到
            doRequestHttp(new SignWorkOutsideInfos(fb.getId(),actualAddr,String.valueOf(actualLat),String.valueOf(actualLon)));

//            real_sign_in.setVisibility(View.GONE);
        }
    }

    private String translateTime(long timeStamp) {
        String time = DateUtil.longToDate(timeStamp, 4);
        String[] strings = time.split(" ");
        if ("09:00:00".equals(strings[1])) {
            return strings[0] + " 上午";
        }else {
            return strings[0] + " 下午";
        }

    }




    /**
     * 根据两个位置的经纬度，来计算两地的距离（单位为KM）
     * 参数为String类型
     *
     * @param lat1Str
     *            用户经度
     * @param lng1Str
     *            用户纬度
     * @param lat2Str
     *            商家经度
     * @param lng2Str
     *            商家纬度
     * @return
     */
    public String getDistance(String lat1Str, String lng1Str, String lat2Str, String lng2Str) {
        Double lat1 = Double.parseDouble(lat1Str);
        Double lng1 = Double.parseDouble(lng1Str);
        Double lat2 = Double.parseDouble(lat2Str);
        Double lng2 = Double.parseDouble(lng2Str);

        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double difference = radLat1 - radLat2;
        double mdifference = rad(lng1) - rad(lng2);
        double distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(difference / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(mdifference / 2), 2)));
        distance = distance * EARTH_RADIUS;
//		distance = Math.round(distance * 10000) / 10000;
        String distanceStr = distance + "";

//		distanceStr = distanceStr.substring(0, distanceStr.indexOf("."));

        return distanceStr;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==100&&resultCode==200){
            feedback = data.getStringExtra("feedback");
            visit_feedback_button.setVisibility(View.GONE);
            Visit_feedback.setVisibility(View.VISIBLE);
            content_feedback.setText("\u3000\u3000"+feedback);
            MyBusinessTripDetailActivity.this.finish();
        }
    }
    @Override
    protected void onStop() {
        super.onStop();
        if (mLocationClient != null) mLocationClient.stopLocation();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //注销EventBus
        EventBus.getDefault().unregister(this);
    }
}